package com.example.movie.ui.cinema.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.movie.R
import com.example.movie.ui.cinema.SeatTableActivity
import com.example.movie.ui.cinema.view.SeatTable
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton
import kotlinx.android.synthetic.main.selected_ticket.view.*

class SelectedTicketAdapter(
    private val seatTable: SeatTable,
    private val payBtn: QMUIRoundButton
) :
    RecyclerView.Adapter<SelectedTicketAdapter.SelectedTicketViewHolder>() {

    private val items: MutableList<String> = mutableListOf()

    /**
     * 记录已选座位和recycleView的position对应关系
     */
    val itemsMap: MutableMap<String, Int> = mutableMapOf()

    class SelectedTicketViewHolder(selectTicketLayout: View) :
        RecyclerView.ViewHolder(selectTicketLayout)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SelectedTicketViewHolder {
        return SelectedTicketViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.selected_ticket, parent, false)
        )
    }

    override fun getItemCount() = items.size

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: SelectedTicketViewHolder, position: Int) {
        with(holder.itemView) {

            ticket.text = items[position]

            remove_selected_ticket.setOnClickListener {
                val ticket = ticket.text.toString()
                itemsMap[ticket]?.let { ticket -> removeItem(ticket) }
                seatTable.unSelected(
                    ticket.substring(0, ticket.indexOf("排")).toInt(),
                    ticket.substring(ticket.indexOf("排").inc(), ticket.length.dec()).toInt()
                )

                SeatTableActivity.deductTotalPrice(payBtn);
            }
        }

    }

    fun addItem(position: Int, id: String) {
        items.add(position, id)
        itemsMap[id] = position
        notifyItemInserted(position)
    }

    fun removeItem(position: Int) {
        val cancelTicket = items.removeAt(position)
        updateItemMaps(cancelTicket)
        itemsMap.remove(cancelTicket)
        notifyItemRemoved(position)
    }

    /**
     * 更新item对应的索引
     */
    private fun updateItemMaps(cancelTicket: String) {
        var flag = false
        for (entry in itemsMap.entries) {
            if (flag) {
                entry.setValue(entry.value.dec())
            } else if (entry.key == cancelTicket) {
                flag = true
            }
        }

    }
}